package com.cobo.fitness.web.post.services.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cobo.fitness.web.post.entity.Category;
import com.cobo.fitness.web.post.mapper.CategoryMapper;
import com.cobo.fitness.web.post.services.CategoryService;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl  extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public List<Category> saveOrUpdateCategory(String[] categorys) {
        List<Category> existCategorys = lambdaQuery()
                .in(Category::getName, Lists.newArrayList(categorys))
                .list();
        Map<String, List<Category>> filterMap = existCategorys.stream().collect(Collectors.groupingBy(Category::getName));

        List<Category> transCategory = new ArrayList<>();
        for (String Category : categorys) {
            if (filterMap.containsKey(Category)) {
                transCategory.add(filterMap.get(Category).get(0));
            }else {
                Category item = new Category();
                item.setName(Category);
                save(item);
                transCategory.add(item);
            }
        }
        return transCategory;
    }
}